package test;

import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;
import java.awt.event.WindowListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Locale;

import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.UIManager.LookAndFeelInfo;

public class ClientView extends ChatterWindows {
	/**
	 *
	 */
	private static final long serialVersionUID = 1L;
	Socket socket;
	BufferedReader bufferedReader;
	PrintWriter printWriter;
	String dataView = "";

	boolean an = false;
	static String key = "0";
	String port;
	String host;
	TrayIcon trayIcon;
	boolean disPlayNewMess  = false;


	public ClientView(String host, String port)  {
		super("", key);
		try {
			this.host = host;
			this.port = port;
			int portInt = 0;
			try {
				portInt = Integer.parseInt(port);

			} catch (Exception e) {
				System.exit(0);
			}

			socket = new Socket(host, portInt);

			bufferedReader = new BufferedReader(new InputStreamReader(
					socket.getInputStream(), "UTF-8"));
			printWriter = new PrintWriter(new OutputStreamWriter(
					socket.getOutputStream(), "UTF-8"));

			String welcome = bufferedReader.readLine();

			JOptionPane.showMessageDialog(null, welcome);
			key = JOptionPane.showInputDialog("Client please input key:");

			String testData = MaHoa.maHoa(key, "0123456789");


			String testData2 = bufferedReader.readLine();
			if(!testData.equals(testData2)){
				JOptionPane.showMessageDialog(this, "key is wrong", "error", JOptionPane.ERROR_MESSAGE);
				printWriter.println("WRONG5482613483156748");
				printWriter.flush();

				printWriter.close();
				bufferedReader.close();
				System.exit(0);
			}else{
				printWriter.println("OK55678625asd");
				printWriter.flush();
			}

			// nhận tên từ server
			String serverName = bufferedReader.readLine();
			this.name = serverName;


			// chuyển tên đến server
			String name = JOptionPane.showInputDialog("Vui lòng nhập tên:");


			this.panelPic.setName(serverName);
			this.myName = name;

			printWriter.println(name);
			printWriter.flush();


		} catch (UnknownHostException e) {
			JOptionPane.showMessageDialog(this, e.getMessage(), "error",
					JOptionPane.ERROR_MESSAGE);
			System.exit(0);
		} catch (IOException e) {
			JOptionPane.showMessageDialog(this, e.getMessage(), "error",
					JOptionPane.INFORMATION_MESSAGE);
			System.exit(0);
		}

		this.addWindowFocusListener(new WindowFocusListener() {

			@Override
			public void windowLostFocus(WindowEvent e) {
				printWriter.println("lofo2484534498756");
				printWriter.flush();

			}

			@Override
			public void windowGainedFocus(WindowEvent e) {
				printWriter.println("focs875548915464");
				printWriter.flush();
				textFieldSend.setRequestFocusEnabled(true);
			}
		});


		buttonHide.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				an = true;
				ClientView.this.setVisible(false);
			}
		});

		buttonCall.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				printWriter.println("call75315987412369");
				printWriter.flush();

			}
		});

		buttonNewMess.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				printWriter.println("new56474456488948");
				printWriter.flush();
				textFieldSend.requestFocus();

			}
		});

		textFieldSend.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				String conten = textFieldSend.getText();
				conten = MaHoa.maHoa(key, conten);
				printWriter.println(conten);
				printWriter.flush();
				textAreaView.setText(textAreaView.getText()
						+"\n "+myName+"("+Chatter_Util.getCurrentTime()+"): " + textFieldSend.getText());
				textFieldSend.setText("");
				ClientView.this.disPlayNewMess = false;
				ClientView.this.newMess(false);

				if (buttonNewMess.isEnabled()) {// button new message (letter) is enable => người kia ko đọc
					lblReadAlready.setText("Chưa đọc");
				}

			}
		});

		textFieldSend.addKeyListener(new KeyAdapter() {

			@Override
			public void keyPressed(KeyEvent e) {
				super.keyPressed(e);
				//System.out.println(e.getKeyCode());
				if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
					System.out.println("hide");
					ClientView.this.setVisible(false);
				}

			}

			@Override
			public void keyReleased(KeyEvent arg0) {
				// TODO Auto-generated method stub
				super.keyReleased(arg0);

				if (checkTempView.isSelected()) {
					String content = textFieldSend.getText();
					content = MaHoa.maHoa(key, content);
					content = ChatterWindows.TEMP_VIEW_STRING + content;
					printWriter.println(content);
					printWriter.flush();
				}
			}



		});

		textAreaView.addMouseListener(new MouseListener() {

			@Override
			public void mouseReleased(MouseEvent e) {
				// TODO Auto-generated method stub

			}

			@Override
			public void mousePressed(MouseEvent e) {

			}

			@Override
			public void mouseExited(MouseEvent e) {
				// TODO Auto-generated method stub

			}

			@Override
			public void mouseEntered(MouseEvent e) {
				// TODO Auto-generated method stub

			}

			@Override
			public void mouseClicked(MouseEvent e) {
				// TODO Auto-generated method stub

			}
		});
		this.setTitle("client "+Const.VERSION+" to server:"+host+"p:"+port);
		textAreaView.setAutoscrolls(true);

		setIconImage(Toolkit.getDefaultToolkit().getImage(RunServer.class.getResource("/test/chat.png")));

		setLocationRelativeTo(null);
		setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
		setVisible(true);

		addWindowListener(new WindowListener() {

			@Override
			public void windowOpened(WindowEvent e) {
				// TODO Auto-generated method stub

			}

			@Override
			public void windowIconified(WindowEvent e) {
				// TODO Auto-generated method stub

			}

			@Override
			public void windowDeiconified(WindowEvent e) {
				// TODO Auto-generated method stub

			}

			@Override
			public void windowDeactivated(WindowEvent e) {
				// TODO Auto-generated method stub

			}

			@Override
			public void windowClosing(WindowEvent e) {
				try {
					int y = JOptionPane.showConfirmDialog(ClientView.this, "Bạn muốn thoát phải không ?", "Exist ? ", JOptionPane.YES_NO_OPTION);
					if(y == JOptionPane.NO_OPTION){
						return;
					}

					printWriter.println("exitakilskdj");
					printWriter.flush();
					bufferedReader.close();
					printWriter.close();
					socket.close();
					System.exit(0);
				} catch (IOException e1) {
					e1.printStackTrace();
				}

			}

			@Override
			public void windowClosed(WindowEvent e) {
				// TODO Auto-generated method stub

			}

			@Override
			public void windowActivated(WindowEvent e) {
				// TODO Auto-generated method stub

			}
		});


		textAreaView.setText("welcome...");
		textAreaView.setFont(new Font("Times New Roman", 0, 14));
		textFieldSend.requestFocus();

		ThreadClientRead threadC = new ThreadClientRead(this);
		threadC.start();

		ThreadAutoGC threadAutoGC = new ThreadAutoGC();
		threadAutoGC.start();

		new Thread(new Runnable() {
			
			@Override
			public void run() {
				ClientView.this.initSystemtTray();
				ClientView.this.trayIcon.setToolTip("Nhan_chatter client to server:"+ClientView.this.host+"p:"+ClientView.this.port);
			}
		}).start();
		


	}


	public Socket getSocket() {
		return socket;
	}

	public void setSocket(Socket socket) {
		this.socket = socket;
	}

	public BufferedReader getBufferedReader() {
		return bufferedReader;
	}

	public void setBufferedReader(BufferedReader bufferedReader) {
		this.bufferedReader = bufferedReader;
	}

	public PrintWriter getPrintWriter() {
		return printWriter;
	}

	public void setPrintWriter(PrintWriter printWriter) {
		this.printWriter = printWriter;
	}

	public String getDataView() {
		return dataView;
	}

	public void setDataView(String dataView) {
		this.dataView = dataView;
	}





	private void initSystemtTray() {
		trayIcon =null;
		if (SystemTray.isSupported()) {
		    SystemTray tray = SystemTray.getSystemTray();
		    Image image = Toolkit.getDefaultToolkit().getImage(RunServer.class.getResource("/test/c.png"));

		    ActionListener exitListener = new ActionListener() {
		        public void actionPerformed(ActionEvent e) {
					try {
//						bufferedReader.close();
//						printWriter.println("exitakilskdj");
//						printWriter.flush();
//						socket.close();
//						printWriter.close();
						System.exit(0);
					} catch (Exception e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
		        }
		    };

		    PopupMenu popup = new PopupMenu();
		    MenuItem defaultItem = new MenuItem("Exit");
		    defaultItem.addActionListener(exitListener);
		    popup.add(defaultItem);

		    trayIcon = new TrayIcon(image, "Nhan chatter", popup);


//		    ActionListener actionListener = new ActionListener() {
//		        @SuppressWarnings("null")
//				public void actionPerformed(ActionEvent e) {
//		            TrayIcon trayIcon = null;
//					trayIcon.displayMessage("Action Event",
//		                "An Action Event Has Been Performed!",
//		                TrayIcon.MessageType.INFO);
//		        }
//		    };
		    trayIcon.addMouseListener(new MouseListener() {

				@Override
				public void mouseReleased(MouseEvent e) {

				}

				@Override
				public void mousePressed(MouseEvent e) {
					// TODO Auto-generated method stub

				}

				@Override
				public void mouseExited(MouseEvent e) {
					// TODO Auto-generated method stub

				}

				@Override
				public void mouseEntered(MouseEvent e) {
					// TODO Auto-generated method stub

				}

				@Override
				public void mouseClicked(MouseEvent e) {
					int count = e.getClickCount();
					if(count == 2){
						ClientView.this.setVisible(true);
						an = false;
					}

				}
			});

		    trayIcon.setImageAutoSize(true);
//		    trayIcon.addActionListener(actionListener);
//		    trayIcon.addMouseListener(mouseListener);
		    trayIcon.addActionListener(new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent e) {
					ClientView.this.setVisible(true);
					an = false;

				}
			});

		    try {
		        tray.add(trayIcon);
		    } catch (AWTException e) {
		        System.err.println("TrayIcon could not be added.");
		    }

		} else {
		    //  System Tray is not supported
		}
	}

}
